Page({
    data: {
      formData: {
        name: '',
        idCard: '',
        phone: '',
        grade: '',
        class: '',
        teacherName: '',
        photo: '',
        privacyAgreed: false,
        major: ''
      },
      selectedGradeText: '',
      errors: {},
      gradeOptions: [
        { name: '2020级', value: '2020' },
        { name: '2021级', value: '2021' },
        { name: '2022级', value: '2022' },
        { name: '2023级', value: '2023' }
      ],
      showGradeSelector: false,
      isFormValid: false,
      applyStatus: '',
      applyInfo: null,
      refuseReason: '',
      showForm: true
    },
  
    onLoad() {
      const userinfo = wx.getStorageSync('userinfo');
      const phone = userinfo ? userinfo.user : '';
      if (!phone) return;
      wx.showLoading({ title: '加载中' });
      wx.request({
        url: getApp({}).globalData.baseUrl + '/schoolfellow/query',
        method: 'POST',
        data: { phone },
        success: (res) => {
          wx.hideLoading();
          if (res.data && res.data.status === 200 && res.data.data) {
            const info = res.data.data;
            this.setData({
              applyStatus: info.status,
              applyInfo: info,
              refuseReason: info.refuse_reason || '',
              showForm: info.status === '拒绝',
              formData: info.status === '拒绝' ? {
                name: info.name,
                idCard: info.id_card,
                phone: info.phone,
                grade: info.grade,
                class: info.class,
                teacherName: info.teacher_name,
                photo: info.photo_url,
                privacyAgreed: !!info.privacy_agreed,
                major: info.major || ''
              } : this.data.formData,
              selectedGradeText: info.status === '拒绝' ? info.grade + '级' : ''
            });
          } else if (res.data && res.data.status === 404) {
            this.setData({
              showForm: true,
              applyStatus: '',
              applyInfo: null
            });
          }
        },
        fail: () => {
          wx.hideLoading();
        }
      });
    },
  
    updateFormValid() {
      const { formData, errors } = this.data;
      const isValid = formData.name &&
        formData.idCard &&
        formData.phone &&
        formData.grade &&
        formData.class &&
        formData.teacherName &&
        formData.photo &&
        formData.privacyAgreed &&
        formData.major &&
        Object.values(errors).every(error => !error);
      this.setData({ isFormValid: isValid });
    },
  
    onNameInput(e) {
      this.setData({ 'formData.name': e.detail }, this.updateFormValid);
      this.validateName();
    },
  
    onIdCardInput(e) {
      this.setData({ 'formData.idCard': e.detail }, this.updateFormValid);
      this.validateIdCard();
    },
  
    onPhoneInput(e) {
      this.setData({ 'formData.phone': e.detail }, this.updateFormValid);
      this.validatePhone();
    },
  
    onClassInput(e) {
      this.setData({ 'formData.class': e.detail }, this.updateFormValid);
      this.validateClass();
    },
  
    onTeacherNameInput(e) {
      this.setData({ 'formData.teacherName': e.detail }, this.updateFormValid);
      this.validateTeacherName();
    },
  
    onSelectGrade() {
      this.setData({ showGradeSelector: true });
    },
  
    onGradeSelected(event) {
      const { name, value } = event.detail;
      this.setData({
        'formData.grade': value,
        selectedGradeText: name,
        showGradeSelector: false
      }, this.updateFormValid);
      this.validateGrade();
    },
  
    onGradeSelectorClose() {
      this.setData({ showGradeSelector: false });
    },
  
    onPrivacyChange(e) {
      this.setData({
        'formData.privacyAgreed': e.detail.value.length > 0
      }, this.updateFormValid);
    },
  
    chooseImage() {
      const that = this;
      wx.chooseImage({
        count: 1,
        success(res) {
          that.setData({
            'formData.photo': res.tempFilePaths[0]
          }, that.updateFormValid);
          that.validatePhoto();
        }
      });
    },
  
    validateName() {
      const name = this.data.formData.name;
      this.setData({
        'errors.name': name ? '' : '请输入姓名'
      });
    },
  
    validateIdCard() {
      const idCard = this.data.formData.idCard;
      const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      let error = '';
      if (!idCard) {
        error = '请输入身份证号';
      } else if (!idCardReg.test(idCard)) {
        error = '请输入正确的身份证号';
      }
      this.setData({ 'errors.idCard': error });
    },
  
    validatePhone() {
      const phone = this.data.formData.phone;
      const phoneReg = /^1[3-9]\d{9}$/;
      let error = '';
      if (!phone) {
        error = '请输入手机号';
      } else if (!phoneReg.test(phone)) {
        error = '请输入正确的手机号';
      }
      this.setData({ 'errors.phone': error });
    },
  
    validateGrade() {
      const grade = this.data.formData.grade;
      this.setData({
        'errors.grade': grade ? '' : '请选择年级'
      });
    },
  
    validateClass() {
      const className = this.data.formData.class;
      this.setData({
        'errors.class': className ? '' : '请输入班级'
      });
    },
  
    validateTeacherName() {
      const teacherName = this.data.formData.teacherName;
      this.setData({
        'errors.teacherName': teacherName ? '' : '请输入班主任姓名'
      });
    },
  
    validatePhoto() {
      const photo = this.data.formData.photo;
      this.setData({
        'errors.photo': photo ? '' : '请上传照片'
      });
    },
  
    onMajorInput(e) {
      this.setData({ 'formData.major': e.detail }, this.updateFormValid);
      this.validateMajor();
    },
  
    validateMajor() {
      const major = this.data.formData.major;
      this.setData({
        'errors.major': major ? '' : '请输入专业'
      });
    },
  
    onSubmit() {
      if (!this.data.isFormValid) {
        wx.showToast({
          title: '请完善所有必填信息',
          icon: 'none'
        });
        return;
      }
  
      wx.showLoading({
        title: '提交中'
      });
  
      const userinfo = wx.getStorageSync('userinfo');
      const phone = userinfo ? userinfo.user : '';
      const isUpdate = this.data.applyStatus === '拒绝' && this.data.applyInfo;
      wx.uploadFile({
        url: getApp({}).globalData.baseUrl + (isUpdate ? '/schoolfellow/update' : '/schoolfellow/apply'),
        filePath: this.data.formData.photo,
        name: 'photo',
        formData: {
          name: this.data.formData.name,
          idCard: this.data.formData.idCard,
          phone: this.data.formData.phone,
          grade: this.data.formData.grade,
          class: this.data.formData.class,
          teacherName: this.data.formData.teacherName,
          privacyAgreed: this.data.formData.privacyAgreed,
          userPhone: phone,
          major: this.data.formData.major,
          id: isUpdate ? this.data.applyInfo.id : undefined
        },
        success: (res) => {
          wx.hideLoading();
          const data = JSON.parse(res.data);
          if (data.status === 200) {
            wx.showToast({
              title: '提交成功',
              icon: 'success'
            });
            this.onLoad();
          } else {
            wx.showToast({
              title: data.message || '提交失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({
            title: '提交失败',
            icon: 'none'
          });
        }
      });
    }
  });
  